package com.zxbg.controller;

import com.zxbg.service.proportalService.PersonalCenterService;
import com.zxbg.service.publicService.SearchPersonService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Map;
import java.util.UUID;

@RestController
public class PublicController {
    @Autowired
    SearchPersonService searchPersonService;
    @Autowired
    PersonalCenterService personalCenterService;

    @PostMapping("/searchPerson")
    public Result getEmployeeByName(@RequestBody String employee_name) {
        return new Result(Code.GET_OK, searchPersonService.getEmployeeByName(employee_name));
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception {
        String file_name = file.getOriginalFilename();
        String upload = request.getServletContext().getRealPath("");
        String path = upload + "/uploadFiles/";
        String suffix = file_name.substring(file_name.lastIndexOf(".") + 1, file_name.length());
        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        FileUtils.copyInputStreamToFile(file.getInputStream(),new File(path + filename));
        return new Result(Code.SAVE_OK, filename);
    }

    @PostMapping("/uploadBase")
    public Result uploadBase(@RequestBody Map<String, String> map, HttpServletRequest request, @RequestHeader String employee_id, @RequestHeader Integer tenant_id) throws Exception {
        //将base64 转换成 MultipartFile
        String base64Imager = map.get("file");
        MultipartFile file = BASE64DecodedMultipartFileUtil.base64ToMultipart(base64Imager);
        Result result = upload(file, request);
        String newUrl = (String)result.getData();
        personalCenterService.updateAvatarImg(newUrl, employee_id, tenant_id);
        return new Result(Code.UPDATE_OK, newUrl);
    }
}
